<template>
  <div class="uploadHealth">
    <el-dialog :visible.sync="fileUpDialogVisible" title="病情上传" :close-on-click-modal="false">
     <el-form :model="dataForm" ref="dataForm" label-width="100px" style='width: 600px; margin-left:20px;' :rules="roleRules">
       <el-form-item label="病情类型" prop="healthType">
         <el-radio-group v-model="dataForm.healthType">
           <el-radio :label="item.value" :key="item.value" v-for="item in healthTypeList">{{item.label}}</el-radio>
         </el-radio-group>
       </el-form-item>
       <el-form-item label="病情日期" prop="healthDate">
         <el-date-picker v-model="dataForm.healthDate" type="datetime"
                         value-format="yyyy-MM-dd hh:mm:ss"></el-date-picker>
       </el-form-item>

       <el-form-item label="病情详情" prop="healthDesc">
         <el-input type="textarea" v-model="dataForm.healthDesc" :rows="5" :cols="30"></el-input>
       </el-form-item>

        <el-form-item>
         <el-upload
            class="upload-demo"
            drag
            :auto-upload="false"
            :action="uploadUrl"
            ref="upload"
            :before-upload="fnBeforeUpload"
            :on-remove="fnUploadRemove"
            :on-exceed="fnUploadExceed"
            :on-change="fnUploadChange"
            :http-request="fnUploadRequest"
            :limit = 'limit'
            :disabled="disabled"
            :file-list="fileList"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">注：目前仅支持上传图片和视频文件且大小不能超过50M</div>
           <!--<div class="el-upload-tip" slot="tip">
             <ul style="margin-top: 10px;">
               <li>1、目前仅支持PDF格式文件上传</li>
               <li>2、至少上传一个，最多上传10个文件</li>
               <li>3、每个文件大小不能超过20M</li>
             </ul>
           </div>-->
          </el-upload>

        </el-form-item>
      </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="fileUpDialogVisible=false">取消</el-button>
          <el-button @click="makeimport(true)" :loading="submitLoading" type="primary">提交，再一次</el-button>
          <el-button @click="makeimport(false)" :loading="submitLoading" type="primary">提交</el-button>
       </div>
    </el-dialog>
  </div>
</template>
<script>
import * as message from "@/constants/message";
import ComponentApi from "@/api/components/component";
import CustomerApi from "@/api/customer/customer";
import * as Constants from "@/constants/constants";

export default {
  name: 'uploadHealth',
  props: {
    /*limit: {
      type: Number,
      default: null
    },*/
    relationId: {
      type: Number,
      default: null
    },
    /*relationType: {
      type: Number,
      default: null
    },*/
    idCard: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      dataForm: {
        relationId:"",
        fileList:[],
        relationType:1,
        idCard:"",
        healthType:"",
        healthDate:"",
        healthDesc:""
      },
      ossClient: null,
      chooseFileLength: 0,
      limit: 8,
      uploadUrl: '',
      fileList: [],
      //病情类型（1.症状 2.检查结果 3.诊断 4.治疗 5.康复情况）
      healthTypeList: [
        { label: '症状', value: 1 },
        { label: '检查结果', value: 2 },
        { label: '诊断', value: 3 },
        { label: '治疗', value: 4 },
        { label: '康复情况', value: 5 }
      ],
      uploadHeaders: {
        authorization: ''
      },
      uploadFileList: [],
      fileUpDialogVisible: false,
      submitLoading: false,
      disabled: false,
      roleRules: {
        healthType: [
          { required: true, message: "请选择病情类型", trigger: "change" },
        ],
        healthDate:[
          { required: true, message: '请选择病情日期', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    relationId(value) {
      this.dataForm.relationId = value
    },
    /*relationType(value) {
      this.dataForm.relationType = value
    },*/
    idCard(value) {
      this.dataForm.idCard = value
    }
  },
  methods: {
    async fnUploadRequest (option) {
      try {
        const _this = this
        // 已经上传过的不处理：情景先上传成功3个，后补充1个，之前3个会循环调用。
        if (option && option.response && option.response.url) {
          return
        }
        // 当前上传的文件
        let file = option.file
        const fileName = file.name
        // 避免文件名带有多个.
        let fileNameArr = fileName.split("\.");
        const fileType = fileNameArr[fileNameArr.length-1];
        const newName = _this.$Utils.mathRand19() +"."+ fileType;
        const storeAs = Constants.OSS_WEB_URL + 'report/' + newName;
        // TODO 测试 注释上传动作
        _this.ossClient.put(storeAs, file, {}).then(
          function (ret) {
            if (ret.res.statusCode == 200) {
              let realUrl = ret.url.replace(Constants.OSS_URL,Constants.OSS_REAL_URL);
              ret.url = realUrl;
              _this.uploadFileList.push(realUrl)
              // 值回传
              option.response = ret
              return ret
            } else {
              option.onError('上传失败')
            }
          }
        ).catch(function (err) {
          console.error(err)
        })
      } catch (error) {
        console.error(error)
        this.disabled = false
        option.onError('上传失败')
        this.$error(error.message)
      }
    },
    /*async fnUploadSuccess (response, file, fileLists) {
      // 会执行两次，第一次是因为获取oss token执行了http请求，成功返回会引起这个方法被执行，所以添加这个判断
      if (typeof(response) == "undefined"){
        return;
      }
      /!*console.log('file>>>>' + JSON.stringify(file));
      console.log('response>>>>' + JSON.stringify(response));
      console.log('fileLists>>>>' + JSON.stringify(fileLists));*!/
      let _this = this
      _this.uploadFileList.push(response.url)
      console.log('上传成功_this.uploadFileList>>>>>>' + _this.uploadFileList)
    },*/
    fnUploadChange (file, fileList) {
      this.chooseFileLength = fileList.length
    },
    fnUploadRemove (file, fileList) {
      this.chooseFileLength = fileList.length
    },
    /**
     * el-upload
     * on-exceed	文件超出个数限制时的钩子
     *  */
    fnUploadExceed (files, fileList) {
      let _this = this
      // _this.$message.warning(`当前限制选择 ${_this.files} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      _this.$message.warning(`当前限制最多上传 ${_this.files} 个文件!`)
    },
    fnBeforeUpload (file) {
      const result = this.$Utils.matchType(file.name);
      if (result != 'image') {
        this.$message.error('文件上传格式不支持!');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 50;
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 50MB!');
        return false;
      }
      return true;
    },
    makeimport(again) {
      let _this = this
      _this.submitLoading = true

      // 判断是否有选择文件
      if (_this.chooseFileLength == 0){
        // 调用上传病情接口 customerHealthUpload
        CustomerApi.customerHealthUpload(_this.dataForm)
          .then(res => {
            _this.$Utils.notifySuccess()
            if (again){
              _this.$refs.dataForm.resetFields()
              _this.fileList = []
              _this.uploadFileList = []
              _this.chooseFileLength = 0
              _this.dataForm.fileList = []
            }else {
              _this.fileUpDialogVisible = false
            }
          }).catch(error => {
          _this.$notify.error({
            title: message.TITLE_ERROR,
            message: "上传失败，请稍后重试"
          })
        })
        _this.submitLoading = false

      }else{

        // 请求oss，获取授权
        ComponentApi.uploadOss().then(res => {
          let OSS = require('ali-oss')
          _this.ossClient = new OSS({
            region: Constants.OSS_REGION,
            accessKeyId: res.data.accessKeyId,
            accessKeySecret: res.data.accessKeySecret,
            stsToken: res.data.securityToken,
            bucket: Constants.OSS_BUCKET
          })

          _this.$refs.upload.submit()
          const interval = setInterval(() => {
            if (_this.uploadFileList.length>0 && _this.uploadFileList.length == _this.chooseFileLength){
              _this.dataForm.fileList = _this.uploadFileList
              // 调用上传病情接口 customerHealthUpload
              CustomerApi.customerHealthUpload(_this.dataForm)
                .then(res => {
                  _this.$Utils.notifySuccess()
                  if (again){
                    _this.$refs.dataForm.resetFields()
                    _this.fileList = []
                    _this.uploadFileList = []
                    _this.chooseFileLength = 0
                    _this.dataForm.fileList = []
                  }else {
                    _this.fileUpDialogVisible = false
                  }
                })
                .catch(error => {
                  _this.$notify.error({
                    title: message.TITLE_ERROR,
                    message: "上传失败，请稍后重试"
                  })
                })

              // 使用$emit出发父组件的自定义事件
              //this.$emit('uploadHealthList', this.uploadFileList)
              //console.log(666,JSON.stringify(this.uploadFileList))
              _this.submitLoading = false
              clearInterval(interval);
            }
          }, 1000)
        })

      }

    },
    handleCreate() {
      this.fileList = []
      this.uploadFileList = []
      this.fileUpDialogVisible = true
    }
  }

}
</script>
<style>
</style>
